package com.nycreativity.elecreativity.service

import com.alibaba.druid.pool.DruidDataSource
import com.nycreativity.elecreativity.util.BatchSQL
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.sql.Connection
import java.sql.PreparedStatement
import javax.annotation.Resource

@Service
class BatchSQLService {

    @Resource
    lateinit var dataSource: DruidDataSource

    /**
     * 执行批量插入
     * @param values 内部属性必须被{@link com.nycreativity.elecreativity.util.BulkInsert.Column}标记过
     */
    @Transactional
    fun execute(values: List<Any>) {
        var prepareStatement: PreparedStatement? = null
        var connection: Connection? = null
        try {
            val insertSql = BatchSQL.insert(values = values)
            connection = dataSource.connection
            prepareStatement = connection.prepareStatement(insertSql)
            prepareStatement.execute()
        } finally {
            prepareStatement?.close()
            connection?.close()
        }
    }

}